//package com.lzs.common.config;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import org.apache.tomcat.util.http.ResponseUtil;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Map;
//
//public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
//    private AuthenticationManager authenticationManager;
//    private JwtTokenUtil jwtTokenUtil;
//
//    public TokenLoginFilter(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil) {
//        this.authenticationManager = authenticationManager;
//        this.jwtTokenUtil = jwtTokenUtil;
//        this.setPostOnly(false);
//        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
//    }
//
//    @Override
//    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
//        try {
//            Map<String, String[]> map = req.getParameterMap();
//            String username = map.get("username")[0];
//            String password = map.get("password")[0];
//            User user = new User(username, password, new ArrayList<>());
//            User user1 = new ObjectMapper().readValue(req.getInputStream(), User.class);
//            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), new ArrayList<>()));
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//    /**
//     * 登录成功
//     */
//    @Override
//    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication auth) throws IOException, ServletException {
//        User user = (User)auth.getPrincipal();
//        String token = jwtTokenUtil.createToken(user.getUsername());
//        HashMap<Object, Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("user",user);
//        map.put("loginName",user.getUsername());
//        ResponseUtil.out(response, Result.ok(map));
//    }
//
//    /**
//     * 登录失败
//     */
//    @Override
//    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
//        ResponseUtil.out(response, Result.error("登录失败"));
//    }
//}
